package com.chen.netty;

import com.alibaba.fastjson.JSON;
import com.chen.api.RpcRequest;
import com.chen.api.RpcResponse;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

public class HttpClientHandler extends SimpleChannelInboundHandler<HttpObject> {

    private RpcResponse rpcResponse;
    private RpcRequest rpcReq;

    public HttpClientHandler(RpcRequest rpcReq) {
        this.rpcReq = rpcReq;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String reqJson = JSON.toJSONString(rpcReq);
        System.out.println("request json:"+ reqJson);
        URI uri = new URI("/");
        FullHttpRequest request =
                new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,uri.toASCIIString(), Unpooled.wrappedBuffer(reqJson.getBytes("UTF-8")));
        request.headers().add(HttpHeaderNames.HOST,"localhost");
        request.headers().add(HttpHeaders.Names.CONTENT_TYPE, "application/json");
        request.headers().add(HttpHeaderNames.CONNECTION,HttpHeaderValues.KEEP_ALIVE);
        request.headers().set(HttpHeaderNames.CONTENT_LENGTH,request.content().readableBytes());
        ctx.writeAndFlush(request);

    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if (msg instanceof HttpResponse) {
            HttpResponse response = (HttpResponse) msg;

            System.out.println("STATUS: " + response.getStatus());
            System.out.println("VERSION: " + response.getProtocolVersion());
            System.out.println();

            if (!response.headers().isEmpty()) {
                for (String name: response.headers().names()) {
                    for (String value: response.headers().getAll(name)) {
                        System.out.println("HEADER: " + name + " = " + value);
                    }
                }
                System.out.println();
            }

            if (HttpHeaders.isTransferEncodingChunked(response)) {
                System.out.println("CHUNKED CONTENT {");
            } else {
                System.out.println("CONTENT {");
            }
        }
        if (msg instanceof HttpContent) {
            HttpContent content = (HttpContent) msg;

            System.out.print(content.content().toString(CharsetUtil.UTF_8));
            System.out.flush();

            if (content instanceof LastHttpContent) {
                System.out.println("} END OF CONTENT");
            }

            String respJson  = content.content().toString(CharsetUtil.UTF_8);
            rpcResponse = JSON.parseObject(respJson, RpcResponse.class);
            ctx.close();
        }
    }

    public RpcResponse getResponse(){
        return rpcResponse;
    }

    @Override
    public void exceptionCaught(
            ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

}
